<?php

/*
 * Copyright (C) 2014 Administrator.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
 * MA 02110-1301  USA
 */

class Uc extends Controller {

    const COOKIEXP = 36000;

    /**
     * 
     * @param type $ControllerName
     * @param type $Action
     * @param type $QueryString
     */
    public function __construct($ControllerName, $Action, $QueryString) {
        parent::__construct($ControllerName, $Action, $QueryString);
        $this->loadModel('Db');
        $this->loadModel('User');
    }

    /**
     * 注册
     */
    public function Reg() {
        global $config;
        $this->loadModel('WechatSdk');
        $this->loadModel('Util');
        if ($config->wechatVerifyed) {
            $Wd = $this->getOpenId(false, true);
            // 微信用户资料
            $WechatUserInfo = WechatSdk::getUserInfo($Wd->accesstoken, $Wd->openid);
            $this->Smarty->assign('head', preg_replace("/\/0/", "", $WechatUserInfo['headimgurl']));
            $this->Smarty->assign('address', $WechatUserInfo['province'] . $WechatUserInfo['city']);
            $this->Smarty->assign('sex', $this->wechatSexConv($WechatUserInfo['sex']));
            $this->Smarty->assign('openid', $Wd->openid);
        } else {
            $address = $this->Util->ipConvAddress($this->getIp());
            $this->Smarty->assign('head', '');
            $this->Smarty->assign('address', $address->region . $address->city);
            $this->sCookie('regtoken', $this->getRegToken());
            $this->Smarty->assign('sex', '');
            $this->Smarty->assign('openid', '');
        }
        $this->show();
    }

    /**
     * 登陆页面
     * @param type $Query
     */
    public function login($Query) {
        #echo $this->server('HTTP_REFERER');
        $this->sCookie('regtoken', $this->getRegToken());
        $this->show();
    }

    /**
     * 
     * @global type $config
     * @return type
     */
    private function getRegToken() {
        global $config;
        $this->loadModel('Secure');
        $ip = $this->getIp();
        return $this->Secure->DesEncrypt($ip . date("Y-m-d"), $config->wshop_salt);
    }

    /**
     * ajax登陆
     */
    public function AjaxLogin() {
        if ($this->getRegToken() == $this->pCookie('regtoken')) {
            $uid = $this->User->userLogin($this->pPost('account'), $this->pPost('password'));
            if ($uid !== false) {
                $this->sCookie('uid', $uid, 3153600);
                $this->sCookie('uctoken', $this->User->genUcToken($uid), 3153600);
                echo 1;
            } else {
                echo 0;
            }
        } else {
            echo 0;
        }
    }

    /**
     * ajax注册
     */
    public function AjaxReg() {
        if ($this->getRegToken() == $this->pCookie('regtoken')) {

            if ($this->User->userCheckExt('client_phone', $this->post('phone'))) {
                die('2');
            }

            if ($this->User->userCheckExt('client_name', $this->post('name'))) {
                die('3');
            }

            if ($this->User->userCheckExt('client_email', $this->post('email'))) {
                die('4');
            }

            /**
             * token validated
             */
            $RegSQL = "INSERT INTO clients (`client_password`,`client_email`,client_name,client_sex,client_phone,client_birth,client_address,client_introducer,client_wechat_openid,client_joindate,client_money) VALUES ('%s','%s','%s','%s','%s','%s','%s',%s,'%s',CURRENT_DATE(),'%s');";
            $RegSQL = sprintf($RegSQL, $this->User->genUserPassword($this->post('password')), $this->post('email'), $this->post('name'), $this->post('sex'), $this->post('phone'), '0000-00-00', $this->post('address'), 0, $this->post('openid'), 0);
            # echo $RegSQL;
            $Uid = $this->Db->query($RegSQL);
            if ($Uid) {
                $RegSQL2 = sprintf("INSERT INTO client_infos (`client_id`,`openid`,`headimg`,`dir_introducer`,`top_introducer`) VALUES (%s,'%s','%s',%s,%s);", $Uid, $this->post('openid'), $this->post('head'), 0, 0);
                // $this->Db->query(sprintf("INSERT INTO client_info_exts (`client_id`,`openid`,`bbname`,`bbage`) VALUES (%s,'%s','%s','%s');", $Uid, $this->post('openid'), $this->post('bbname'), $this->post('bbage')));
                $this->Db->query($RegSQL2);
                if ($Uid > 0) {
                    // set cookie
                    $this->sCookie('uid', $Uid, Uc::COOKIEXP);
                    $this->sCookie('uctoken', $this->User->genUcToken($Uid), Uc::COOKIEXP);
                }
                echo $Uid > 0 ? 1 : 0;
            } else {
                echo 0;
            }
        } else {
            echo 0;
        }
    }

    /**
     * user Home
     */
    public function home() {
        $Uid = intval(isset($_COOKIE['uid']) ? $_COOKIE['uid'] : 0);
        $userInfo = new stdClass();
        if ($Uid === 0) {
            if (Controller::inWechat()) {
                $Openid = $Wd = $this->getOpenId();
                if ($Openid != '') {
                    if (!$this->User->checkUserExt($Openid)) {
                        $this->redirect($this->root . '?/Uc/login');
                    } else {
                        $Uid = $this->Db->query("SELECT `client_id` FROM `clients` WHERE `client_wechat_openid` = '$Openid';");
                        $Uid = intval($Uid[0]['client_id']);
                    }
                    setcookie("uid", $Uid, time() + Uc::COOKIEXP);
                    $userInfo = $this->User->getUserInfo($Uid);
                } else {
                    $this->redirect($this->root . '?/Uc/login');
                }
            } else {
                // 用户不在微信状态 而且未注册
                $this->redirect($this->root . '?/Uc/login');
            }
        } else {
            $userInfo = $this->User->getUserInfo($Uid);
            // cookie持久
            setcookie("uid", $_COOKIE['uid'], time() + Uc::COOKIEXP);
        }

        // 待收货订单计算
        $devliveringCount = $this->Db->query(sprintf("SELECT COUNT(`order_id`) AS `count` FROM `orders` WHERE `status` = 'delivering' AND `client_id` = %s", $Uid));

        $this->Smarty->assign('devliCount', $devliveringCount[0]['count']);
        $this->Smarty->assign('bagRand', intval(rand(1, 3)));
        $this->Smarty->assign('userinfo', (array) $userInfo);
        $this->show();
    }

    /**
     * 
     * @param type $sexInt
     * @return string
     */
    private function wechatSexConv($sexInt) {
        $sex_arr = array('NULL', "m", "f");
        return $sex_arr[($sexInt ? $sexInt : 0)];
    }

    /**
     * companySpread
     */
    public function companySpread() {
        // 统计数据 
        $openid = $this->getOpenId();
        $this->loadModel('User');
        # $userInfo = $this->User->getUserInfo();
        if (!$this->isCompany($openid)) {
            header('Location:' . $this->root . '?/WechatWeb/proxy/');
        } else {
            $openid = $this->getOpenId();
            $spreadData = $this->Db->getOneRow("select sum(readi) as readi,sum(turned) as turned from company_spread_record WHERE com_id = '$openid';");
            $spreadData['turnrate'] = sprintf('%.2f', $spreadData['readi'] > 0 ? ($spreadData['turned'] / $spreadData['readi']) : 0);
            $spreadData['incometot'] = $this->Db->query("SELECT sum(amount) AS amount FROM `company_income_record` WHERE com_id = '$openid';");
            $spreadData['incometot'] = $spreadData['incometot'][0]['amount'] > 0 ? $spreadData['incometot'][0]['amount'] : 0;
            $spreadData['incometod'] = $this->Db->query("SELECT sum(amount) AS amount FROM `company_income_record` WHERE com_id = '$openid' AND to_days(date) = to_days(now());");
            $spreadData['incometod'] = $spreadData['incometod'][0]['amount'] > 0 ? $spreadData['incometod'][0]['amount'] : 0;
            $this->Smarty->assign('stat_data', $spreadData);
            $this->Smarty->assign('title', '我的推广');
            $this->show();
        }
    }

    /**
     * 
     * @param type $Query
     */
    public function ajaxSpreadList($Query) {
        !isset($Query->page) && $Query->page = 0;

        $OpenId = $this->getOpenId();
        $SQLimit = $Query->page * 20 . "," . 20;
        $SpreadSql = "SELECT * FROM `company_spread_record` WHERE `com_id` = '$OpenId' LIMIT $SQLimit;";
        $SpreadList = $this->Db->query($SpreadSql);

        foreach ($SpreadList as $index => $ls) {
            $_data = $this->Db->query("SELECT * FROM `vproductinfo` WHERE `product_id` = $ls[product_id];");
            #var_dump($_data);
            $SpreadList[$index]['pdata'] = $_data[0];
        }

        $this->Smarty->assign('spreadlist', $SpreadList);
        $this->show();
    }

    /**
     * 订单列表
     * @param type $status
     */
    public function orderlist($Query) {
        !isset($Query->status) && $Query->status = '';
        $this->Smarty->assign('status', $Query->status);
        $this->Smarty->assign('title', '我的订单');
        $this->show();
    }

    /**
     * Ajax订单列表
     * @param type
     */
    public function ajaxOrderlist($Query) {
        $uid = intval($_COOKIE['uid']);
        !isset($Query->page) && $Query->page = 0;

        $_SQL_limit = $Query->page * 10 . ",10";
        if ($Query->status == '' || !$Query->status) {
            $SQL = sprintf("SELECT * FROM `orders` WHERE `client_id` = %s AND `client_id` <> 0 AND `status` <> 'canceled' ORDER BY `order_time` DESC LIMIT $_SQL_limit", $uid);
        } else {
            $SQL = sprintf("SELECT * FROM `orders` WHERE `status` = '$Query->status' AND `client_id` = %s AND `client_id` <> 0 AND `status` <> 'canceled' ORDER BY `order_time` DESC LIMIT $_SQL_limit;", $uid);
        }
        # echo $SQL;
        $orders = $this->Db->query($SQL);
        foreach ($orders AS &$_order) {
            $_order['order_time'] = $this->dateTimeFormat($_order['order_time']);
            $_order['data'] = $this->Db->query("SELECT catimg,`pi`.product_name,`pi`.product_id,`sd`.product_count,`sd`.product_discount_price FROM `orders_detail` sd LEFT JOIN `vproductinfo` pi on pi.product_id = sd.product_id WHERE `sd`.order_id = " . $_order['order_id']);
            #echo "SELECT `pi`.product_name,`pi`.product_id,`sd`.product_count,`sd`.product_discount_price FROM `orders_detail` sd LEFT JOIN `vProductInfo` pi on pi.product_id = sd.product_id WHERE `sd`.order_id = " . $_order['order_id'];
        }
        $this->Smarty->assign('orders', $orders);
        $this->show();
    }

    /**
     * 查看订单详情
     * @param type $orderid
     */
    public function viewOrder($orderid) {
        $this->show();
    }

    /**
     * 
     * @param type $timestamp
     * @return string
     */
    private function dateTimeFormat($timestamp) {
        $timestamp = strtotime($timestamp);
        $curTime = time();
        $space = $curTime - $timestamp;
        //1分钟
        if ($space < 60) {
            $string = "刚刚";
            return $string;
        } elseif ($space < 3600) { //一小时前
            $string = floor($space / 60) . "分钟前";
            return $string;
        }
        $curtimeArray = getdate($curTime);
        $timeArray = getDate($timestamp);
        if ($curtimeArray['year'] == $timeArray['year']) {
            if ($curtimeArray['yday'] == $timeArray['yday']) {
                $format = "%H:%M";
                $string = strftime($format, $timestamp);
                return "今天 {$string}";
            } elseif (($curtimeArray['yday'] - 1) == $timeArray['yday']) {
                $format = "%H:%M";
                $string = strftime($format, $timestamp);
                return "昨天 {$string}";
            } else {
                $string = sprintf("%d月%d日 %02d:%02d", $timeArray['mon'], $timeArray['mday'], $timeArray['hours'], $timeArray['minutes']);
                return $string;
            }
        }
        $string = sprintf("%d年%d月%d日 %02d:%02d", $timeArray['year'], $timeArray['mon'], $timeArray['mday'], $timeArray['hours'], $timeArray['minutes']);
        return $string;
    }

    /**
     * 判断是否微代理
     */
    private function isCompany($openid) {
        return $this->Db->query("SELECT `uid` FROM `companys` WHERE `uid` = '$openid';");
    }

    public function selectOrderAddress($Query) {
        !isset($Query->body) && $Query->body = 'false';
        $uid = $this->pCookie('uid');
        $ret = $this->Db->query("SELECT * FROM `client_order_address` WHERE `client_id` = $uid;");
        $this->Smarty->assign('addrs', $ret);
        $this->Smarty->assign('bodyonly', $Query->body == 'true' ? true : false);
        $this->show();
    }

    public function ajaxAddAddress() {
        $uid = $this->pCookie('uid');
        $name = $this->post('name');
        $tel = $this->post('tel');
        $addr = $this->post('addr');
        $ret = $this->Db->query("INSERT INTO `client_order_address` (client_id,`name`,`tel`,`address`) VALUES ($uid,'$name','$tel','$addr');");
        echo $ret;
    }

}
